﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Data;
using System.Reflection;

namespace HZ.Data
{
    public class ModelConvert
    {
        /// <summary>
        /// 根据Model生成DataTable
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="modellist"></param>
        /// <returns></returns>
        public static DataTable GetDataTableFromModel<T>(IList<T> modellist)
        {
            DataTable result = new DataTable();
            Type type = typeof(T);
            foreach (var item in type.GetProperties())
            {
                //增加数据列类型定义
                result.Columns.Add(new DataColumn(item.Name, ChangeType(item.PropertyType)));
            }

            foreach (var item in modellist)
            {
                DataRow row = result.NewRow();
                row.ItemArray = GetObjectArrayFromModel(item);
                result.Rows.Add(row);
            }
            return result;

        }
        /// <summary>
        /// 
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="t"></param>
        /// <returns></returns>
        private static object[] GetObjectArrayFromModel<T>(T t)
        {
            Type type = typeof(T);
            PropertyInfo[] properties = type.GetProperties();
            object[] array = new object[properties.Length];

            for (int i = 0; i < properties.Length; i++)
            {
                array[i] = properties[i].GetValue(t, null);
            }
            return array;
        }

        /// <summary>
        /// 泛型类型 转换为基础类型
        /// </summary>
        /// <param name="conversionType"></param>
        /// <returns></returns>
        private static Type ChangeType(Type conversionType)
        {
            if (conversionType.IsGenericType && conversionType.GetGenericTypeDefinition().Equals(typeof(Nullable<>)))
            {
                System.ComponentModel.NullableConverter nullableConverter
                = new System.ComponentModel.NullableConverter(conversionType);

                conversionType = nullableConverter.UnderlyingType;
            }
            return conversionType;

        }
    }
}
